package com.alipay.rebate.shop.service.admin.impl;

import com.alipay.rebate.shop.constants.*;
import com.alipay.rebate.shop.dao.mapper.*;
import com.alipay.rebate.shop.exceptoin.BusinessException;
import com.alipay.rebate.shop.helper.JpushHelper;
import com.alipay.rebate.shop.helper.LuckyMoneyHelper;
import com.alipay.rebate.shop.helper.MobileCodeInformationHelper;
import com.alipay.rebate.shop.helper.UserIncomeHelper;
import com.alipay.rebate.shop.model.*;
import com.alipay.rebate.shop.pojo.alipay.WithDeawTotal;
import com.alipay.rebate.shop.pojo.mobilecode.SendSmsResponse;
import com.alipay.rebate.shop.pojo.user.admin.WithDrawPageRequest;
import com.alipay.rebate.shop.pojo.user.admin.WithDrawUto;
import com.alipay.rebate.shop.service.admin.AdminWithdrawService;
import com.alipay.rebate.shop.utils.AliUtil;
import com.alipay.rebate.shop.utils.DateUtil;
import com.alipay.rebate.shop.utils.DecimalUtil;
import com.aliyuncs.CommonResponse;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AdminWithdrawServiceImpl  implements AdminWithdrawService {

  private Logger logger = LoggerFactory.getLogger(AdminWithdrawServiceImpl.class);

  @Resource
  private WithDrawMapper withDrawMapper;
  @Resource
  private UserMapper userMapper;
  @Resource
  private UserIncomeHelper userIncomeHelper;
  @Resource
  private LuckyMoneyHelper luckyMoneyHelper;
  @Autowired
  private JpushHelper jpushHelper;
  @Resource
  private JpushSettingsMapper jpushSettingsMapper;
  @Resource
  private MobileCodeInformationHelper informationHelper;
  @Override
  public int insert(WithDraw withDraw) {
    return withDrawMapper.insertWithDrawSelective(withDraw);
  }

  @Override
  public int delete(Long id) {
    return withDrawMapper.deleteById(id);
  }

  @Override
  public int update(WithDraw withDraw) {
    return withDrawMapper.updateByPrimaryKeySelective(withDraw);
  }

  @Override
  public WithDraw get(Long id) {
    return withDrawMapper.selectByPrimaryKey(id);
  }

  @Override
  public List<WithDraw> selectWithDrawRecordByUserId(Long userId) {
    return withDrawMapper.selectWithDrawByUserId(userId);
  }

  @Override
  public PageInfo<WithDrawUto> selectWithDrawByCondition(WithDrawPageRequest withDrawPageRequest) {
    logger.debug("pageSize is: {}",withDrawPageRequest.getPageSize());
    logger.debug("pageNo is: {}",withDrawPageRequest.getPageNo());
    PageHelper.startPage(withDrawPageRequest.getPageNo(),withDrawPageRequest.getPageSize());
    List<WithDrawUto> page =  withDrawMapper.selectWithDrawByCondition(withDrawPageRequest);
    PageInfo<WithDrawUto> pageInfo = new PageInfo<>(page);


    logger.debug("pageInfo is:{}",pageInfo);
    return pageInfo;
  }

  @Override
  public Map selectApplyNumberByTime(Date startTime, Date endTime) {
    return withDrawMapper.selectApplyNumberByTime(startTime,endTime);
  }

  @Override
  public int updateWithDrawRecord(WithDraw withDraw) {


    // 获取到数据库之前的记录
    WithDraw dbRecord = withDrawMapper.selectByPrimaryKey(withDraw.getWithdrawId());

    logger.debug("dbRecord is : {}",dbRecord);

    Long userId = dbRecord.getUserId();
//    // 如果是提现成功状态,减少用户余额或者集分宝
//    reduceUserAmountOrUit(withDraw,dbRecord);

    // 更新提现记录
    withDraw.setHandleTime(new Date());
    int result = withDrawMapper.updateByPrimaryKeySelective(withDraw);

    // 如果进入提现成功状态进行红包奖励
    if(WithDrawConstant.WITHDRAW_SUCCESS == withDraw.getStatus()){

      userIncomeHelper.updateUserIncome(withDraw.getUserId(),WithDrawConstant.WITHDRAW_SUCCESS);

      // 红包奖励
      luckyMoneyHelper.openLuckyMoneyCouponIfNeed(userId,
          LuckyMonCouponConstant.CONDITION_TYPE_WITHDRAW_MONEY,
          null,false);
      jpushHelper.withDrawSuccessPush(String.valueOf(userId));
    }

    int type = -1;

    // 如果提现驳回， 那么发送提现失败通知
    if(WithDrawConstant.WITHDRAW_REJECT == withDraw.getStatus()){
      // 增添回用户减少的集分宝或者金额
      plusUserAmountOrUit(dbRecord);
      // 发送推送通知
      JpushSettings jpushSettings = jpushSettingsMapper.selectByType(JpushSettingsConstant.WITH_FAILED);
      logger.debug("jpushSettings is: {}",jpushSettings);
      jpushHelper.withDrawFailedPush(String.valueOf(userId),jpushSettings);
      if(jpushSettings.getSmsEnable() != null && jpushSettings.getSmsEnable() == 1){
        User user = userMapper.selectById(dbRecord.getUserId());
        String reason = withDraw.getRefuseReason();
        if(StringUtils.isEmpty(reason)){
          reason = "提现驳回";
        }
        SendSmsResponse commonResponse = AliUtil.sendWithDrawSms(user.getPhone(), user.getUserNickName(), reason,
                jpushSettings.getSmsSignName(),
                jpushSettings.getSmsTemplateCode());

        MobileCodeInformation information = informationHelper.getMobileCodeInformation(user.getPhone(),type,jpushSettings.getSmsTemplateCode());
//        informationMapper.insertMobileCodeInformation(information);
        informationHelper.insertMobileCodeInformation(commonResponse,information);
        userIncomeHelper.updateUserIncome(withDraw.getUserId(),3);
      }
      userIncomeHelper.updateUserIncome(userId,WithDrawConstant.WITHDRAW_REJECT);
    }
    return result;
  }



  @Override
  public WithDeawTotal selectWithDrawSuccessMoneyNum() {
    WithDeawTotal withDeawTotal = new WithDeawTotal();
    BigDecimal bigDecimal = withDrawMapper.selectWithDrawSuccessMoneyNum();
    withDeawTotal.setTotal(bigDecimal);
    return withDeawTotal;
  }

  @Override
  public PageInfo<WithDrawUto> selectNotHandleWithDraw(WithDrawPageRequest withDrawPageRequest) {
    logger.debug("pageSize is: {}",withDrawPageRequest.getPageSize());
    logger.debug("pageNo is: {}",withDrawPageRequest.getPageNo());
    PageHelper.startPage(withDrawPageRequest.getPageNo(),withDrawPageRequest.getPageSize());

    if (withDrawPageRequest.getStatus() != null) {
      if (withDrawPageRequest.getStatus() == 0) {
        withDrawPageRequest.setStatus(null);
      }
    }

    List<WithDrawUto> withDrawUtos = withDrawMapper.selectNotHandleWithDraw(withDrawPageRequest);
    PageInfo<WithDrawUto> pageInfo = new PageInfo<>(withDrawUtos);
    return pageInfo;
  }

  @Override
  public PageInfo<WithDrawUto> selectHandleWithDraw(WithDrawPageRequest withDrawPageRequest) {
    logger.debug("pageSize is: {}",withDrawPageRequest.getPageSize());
    logger.debug("pageNo is: {}",withDrawPageRequest.getPageNo());
    PageHelper.startPage(withDrawPageRequest.getPageNo(),withDrawPageRequest.getPageSize());

    if (withDrawPageRequest.getStatus() != null) {
      if (withDrawPageRequest.getStatus() == 0) {
        withDrawPageRequest.setStatus(null);
      }
    }

    List<WithDrawUto> withDrawUtos = withDrawMapper.selectHandleWithDraw(withDrawPageRequest);

    PageInfo<WithDrawUto> pageInfo = new PageInfo<>(withDrawUtos);
    return pageInfo;
  }

  private void plusUserAmountOrUit(WithDraw dbRecord){
      if(dbRecord!=null){
        // 如果是金额提现类型,那么增加用户余额
        if( dbRecord.getType() == WithDrawConstant.WITHDRAW_AMOUNT_TYPE){
          userMapper.plusOrReductVirtualMoneyDirectly(
             null,null,dbRecord.getMoney(),dbRecord.getUserId());
        }
        // 如果是集分宝提现类型, 那么增加用户集分宝
        else if(dbRecord.getType()==WithDrawConstant.WITHDRAW_UIT_TYPE
        ){
          userMapper.plusOrReductVirtualMoneyDirectly(
              DecimalUtil.convertMoneyToUit(dbRecord.getMoney()),
              null,null,dbRecord.getUserId()
          );
        }
        // 否则, 提示提现失败
        else{
          throw new BusinessException("提現失敗", StatusCode.WITH_DRAW_ERROR);
        }
      }else{
        throw new BusinessException("不存在相应提现记录", StatusCode.WITH_DRAW_ERROR);
      }
  }

//  private void reduceUserAmountOrUit(WithDraw withDraw, WithDraw dbRecord){
//    if(WithDrawConstant.WITHDRAW_SUCCESS == withDraw.getStatus()){
//      if(dbRecord!=null){
//        User user = userMapper.selectById(dbRecord.getUserId());
//        // 如果是金额提现类型,那么查看用户余额是否足够提现,减少用户余额
//        if( dbRecord.getType() == WithDrawConstant.WITHDRAW_AMOUNT_TYPE
//            && user.getUserAmount().compareTo(dbRecord.getMoney()) > 0
//        ){
//          userMapper.plusUserAM(dbRecord.getMoney().negate(),dbRecord.getUserId());
//        }
//        // 如果是集分宝提现类型, 那么查看用户集分宝是否足够提现, 减少用户集分宝
//        else if(dbRecord.getType()==WithDrawConstant.WITHDRAW_UIT_TYPE &&
//            user.getUserIntgeralTreasure() > DecimalUtil.convertMoneyToUit(dbRecord.getMoney())
//        ){
//          userMapper.plusUserIntgeral(-DecimalUtil.convertMoneyToUit(dbRecord.getMoney()),dbRecord.getUserId());
//        }
//        // 否则, 提示提现失败
//        else{
//          throw new BusinessException("提現失敗", StatusCode.WITH_DRAW_ERROR);
//        }
//      }else{
//        throw new BusinessException("不存在相应提现记录", StatusCode.WITH_DRAW_ERROR);
//      }
//    }
//  }
}
